package lp.polimi.treefinder.client;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketException;

import lp.polimi.treefinder.utils.ManagingMessage;

/** 
 * TCP implementation of Connection. The server runs each connection to a client on a different thread.
 */
public class DefaultTCPConnection implements Connection {

	private GenericSocket socket;
	private ObjectInputStream ois;
	private ObjectOutputStream oos;

	private String host;
	private int port;

	public DefaultTCPConnection (String host, int port) {
		this.host = host;
		this.port = port;
	}

	public DefaultTCPConnection (GenericSocket socket) {
		this.socket = socket;
	}


	@Override
	public void closeSocket() {
		socket.close();	
	}

	@Override
	public void initialize() throws Exception {
		Socket s = new Socket();
		try {
			s.connect(new InetSocketAddress(host, port));
			socket = new DefaultTCPSocket(s);
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

	@Override
	public ManagingMessage receive() throws StreamCorruptedException, IOException, ClassNotFoundException {
			if (ois == null)
				ois = new ObjectInputStream(socket.getInputStream());
			ManagingMessage message = (ManagingMessage) ois.readObject();
			return message;
	}

	@Override
	public void send(ManagingMessage managingMessage) throws IOException {
			if (oos == null)
				oos = new ObjectOutputStream(socket.getOutputStream());
			oos.writeObject(managingMessage);
	}

	@Override
	public GenericSocket getSocket() {
		return socket;
	}
}
